package cn.baddonkey.photography.agent.node;

import cn.baddonkey.photography.agent.controller.GraphStreamController;
import cn.baddonkey.photography.agent.graph.NodeStatus;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.api.DashScopeResponseFormat;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.cloud.ai.dashscope.chat.MessageFormat;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.fastjson.JSONObject;
import io.reactivex.Flowable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;


public class ImageJudgeNode implements NodeAction {


    private final Map<String, NodeStatus> node2Status;

    private static final String SYSTEM_PROMPT = """
            1、用户给你一段文本，这段文本是对某个摄影照片的描述，你根据描述信息判断这张照片是否有必要做后期处理；
            2、你必须使用json格式来回答问题，你的回答必须有且仅有一个完整的jsonObject，除此之外不能有任何其他无关字符出现在你的回答中；
            3、当照片不需要做后期处理时，你返回的json格式如下：
            {
              "processable": false
            }
            当需要后期处理时，返回json格式如下：
            {
              "processable": true
            }
            当无法明确判断出结果时，判定为无需处理，processable返回false""";

    public ImageJudgeNode(Map<String, NodeStatus> node2Status) {
        this.node2Status = node2Status;
    }

    @Override
    public Map<String, Object> apply(OverAllState state) {
        System.out.println("进入ImageJudgeNode");
        if (!isDone(node2Status)) {
            System.out.println("未完成ImageJudgeNode");
            return Map.of();
        }

        String expanderContent = state.value("expandercontentText", "");
        System.out.println("输出结果");
        System.out.println(expanderContent);
        if (StringUtils.isEmpty(expanderContent)) {
            System.out.println("输出结果为空");
            return Map.of("ImageJudgeNode", false);
        }
        String threadId = state.value("threadId", "");
        final SseEmitter sseEmitter = GraphStreamController.SSE_POOL.get(threadId);
        if (sseEmitter == null) {
            throw new RuntimeException();
        }

        DashScopeApi dashScopeApi = DashScopeApi.builder().baseUrl("https://dashscope.aliyuncs.com")
                .apiKey("sk-83bcb11ec336414e81c6b47b2d66507a").build();
        DashScopeChatModel dashScopeChatModel = DashScopeChatModel.builder().dashScopeApi(dashScopeApi)
                .defaultOptions(DashScopeChatOptions.builder().withModel("qwen3-30b-a3b-instruct-2507")
                        .withStream(true).withResponseFormat(new DashScopeResponseFormat(DashScopeResponseFormat.Type.JSON_OBJECT)).build()).build();

        UserMessage userMessage = new UserMessage.Builder().text(expanderContent).build();
        ChatClient chatClient = ChatClient.builder(dashScopeChatModel).defaultSystem(SYSTEM_PROMPT).build();
        String content = chatClient.prompt(new Prompt(userMessage)).call().content();
        System.out.println("判断结果：" + content);
        JSONObject jsonObject = JSONObject.parseObject(content);

        boolean processable = jsonObject.getBooleanValue("processable");
        return Map.of("ImageJudgeNode", processable);
    }

    private boolean isDone(Map<String, NodeStatus> node2Status) {
        return node2Status.get("ImageIntroNode").equals(NodeStatus.COMPLETED);
    }
}
